package com.nexmo.hangman.dao.abs;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;

import java.io.Serializable;
import java.util.List;

public abstract class AbstractDaoSupport<T extends Serializable, PK extends Serializable>  implements AbstractDao<T, PK> {
    private final SessionFactory sessionFactory;
    private Class<T> entityClass;

    protected AbstractDaoSupport(Class<T> entityClass, SessionFactory sessionFactory) {
        this.entityClass = entityClass;
        this.sessionFactory = sessionFactory;
    }

    protected Session currentSession() {
        return  sessionFactory.getCurrentSession();
    }

    @Override
    public T findById(PK id) {
        return (T)currentSession().get(entityClass, id);
    }

    @Override
    public void saveOrUpdate(T t) {
        sessionFactory.getCurrentSession().saveOrUpdate(t);
    }

    @Override
    public void save(T t) {
        sessionFactory.getCurrentSession().save(t);
    }

    @Override
    public void delete(T t) {
        currentSession().delete(t);
    }

    @Override
    public List<T> findAll() {
        return currentSession().createCriteria(entityClass).list();
    }

    protected Criteria getDefaultCriteria() {
        return currentSession().createCriteria(entityClass);
    }
}
